
import SwiftUI
import GRDB

struct AddressBookImagesView: View {
    @State var images = [(String, UIImage)]()
    @State var thumbnails = [(String, UIImage)]()

    var body: some View {
        List {
            ForEach(images, id: \.0) { text, image in
                VStack {
                    Text(text)
                    Image(uiImage: image)
                }
            }
            ForEach(thumbnails, id: \.0) { text, image in
                VStack {
                    Text(text)
                    Image(uiImage: image)
                }
            }

        }.onAppear(perform: {
            do {
                let dbPool = try DatabasePool(path: addressBookImagesPath)
                let imageRows = try dbPool.read { db in
                    return try Row.fetchAll(db, sql: "SELECT * FROM ABFullSizeImage")
                }
                for row in imageRows {
                    let recordId:Int = row["record_id"]
                    if let data: Data = row["data"], let image = UIImage(data: data) {
                        images.append(("\(recordId)", image))
                    }
                }
                let thumbnailRows = try dbPool.read { db in
                   return try Row.fetchAll(db, sql: "SELECT * FROM ABThumbnailImage")
                }
                for row in thumbnailRows {
                    let recordId:Int = row["record_id"]
                    if let data: Data = row["data"], let image = UIImage(data: data) {
                        thumbnails.append(("\(recordId)", image))
                    }
                }
            } catch {
                print(error)
            }
        })
    }
}

struct AddressBookImagesView_Previews: PreviewProvider {
    static var previews: some View {
        AddressBookImagesView()
    }
}
